package priorityqueue

/*
Copyright @2016 by No.20(zdt3476@163.com)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import "container/heap"

type Itemer interface {
	Value() interface{}
	Priority() int
}

type heapqueue []Itemer

func (hq *heapqueue) Len() int {
	return len(*hq)
}

func (hq *heapqueue) Less(x, y int) bool {
	return (*hq)[x].Priority() > (*hq)[y].Priority()
}

func (hq *heapqueue) Swap(x, y int) {
	(*hq)[x], (*hq)[y] = (*hq)[y], (*hq)[x]
}

func (hq *heapqueue) Push(n interface{}) {
	*hq = append(*hq, n.(Itemer))
}

func (hq *heapqueue) Pop() interface{} {
	item := (*hq)[hq.Len()-1]
	(*hq) = (*hq)[0 : hq.Len()-1]
	return item
}

type PriorityQueue struct {
	hq heapqueue
}

func New() *PriorityQueue {
	pq := &PriorityQueue{
		hq: make([]Itemer, 0),
	}
	heap.Init(&pq.hq)
	return pq
}

func (pq *PriorityQueue) Push(item Itemer) {
	heap.Push(&pq.hq, item)
}

func (pq *PriorityQueue) Pop() Itemer {
	if pq.hq.Len() <= 0 {
		return nil
	}
	return heap.Pop(&pq.hq).(Itemer)
}

func (pq *PriorityQueue) Empty() bool {
	return pq.Size() == 0
}

func (pq *PriorityQueue) Size() int {
	return pq.hq.Len()
}

// O(n)
func (pq *PriorityQueue) Contains(item Itemer) bool {
	for _, i := range pq.hq {
		if i == item {
			return true
		}
	}

	return false
}
